import {
  Popover,
  PopoverContent,
  PopoverTrigger,
} from "@/components/ui/popover";
import { LanguagesIcon } from "lucide-react";
import { useTranslation } from "react-i18next";
import { useCookies } from "react-cookie";
import { Button } from "@/components/ui/button";
import { useState } from "react";
import { LANGUAGE } from "@/constants/cookies";

const languages = [
  { code: "en-US", label: "English", nativeLabel: "English" },
  { code: "zh-CN", label: "中文", nativeLabel: "简体中文" },
];

export default function LanguageSwitcher() {
  const { i18n } = useTranslation();
  const [, setCookie] = useCookies(['language']);
  const [currentLanguage, setCurrentLanguage] = useState(
    languages.find(lang => lang.code === i18n.language) || languages[0]
  );

  const handleLanguageChange = async (languageCode: string) => {
    try {
      // 切换前端语言
      await i18n.changeLanguage(languageCode);
      
      // 更新当前语言状态
      const newLanguage = languages.find(lang => lang.code === languageCode) || languages[0];
      setCurrentLanguage(newLanguage);
      
      // 使用 react-cookie 设置 cookie
      setCookie(LANGUAGE, languageCode, {
        path: '/',
        maxAge: 31536000, // 1 year
        sameSite: 'lax',
      });
    } catch (error) {
      console.error('Error changing language:', error);
    }
  };

  return (
    <Popover>
      <PopoverTrigger asChild>
        <div className="w-20 flex items-center text-sm gap-2 cursor-pointer group">
          <LanguagesIcon size={14} className="text-muted-foreground group-hover:text-primary" />
          <div className="text-muted-foreground group-hover:text-primary">
            {currentLanguage.label}
          </div>
        </div>
      </PopoverTrigger>
      <PopoverContent className="w-auto flex flex-col gap-2">
        {languages.map((language) => (
          <Button
            key={language.code}
            variant={currentLanguage.code === language.code ? "default" : "ghost"}
            size="sm"
            onClick={() => handleLanguageChange(language.code)}
            className="justify-start hover:cursor-pointer"
          >
            {language.nativeLabel}
          </Button>
        ))}
      </PopoverContent>
    </Popover>
  );
}
